extends Control

# 主菜单界面脚本
# 处理主菜单的各种按钮交互

# UI节点引用
@onready var start_button = $VBoxContainer/StartButton
@onready var help_button = $VBoxContainer/HelpButton
@onready var settings_button = $VBoxContainer/SettingsButton
@onready var quit_button = $VBoxContainer/QuitButton

# 存档选择界面引用
@onready var save_selection_panel = $SaveSelectionPanel
@onready var save_buttons_container = $SaveSelectionPanel/VBoxContainer/SaveButtonsContainer
@onready var back_button = $SaveSelectionPanel/VBoxContainer/BackButton

# 存档数据
var save_slots = 5  # 存档槽数量
var save_data = {}  # 存档数据字典

func _ready():
	# 连接按钮信号
	start_button.pressed.connect(_on_start_button_pressed)
	help_button.pressed.connect(_on_help_button_pressed)
	settings_button.pressed.connect(_on_settings_button_pressed)
	quit_button.pressed.connect(_on_quit_button_pressed)
	back_button.pressed.connect(_on_back_button_pressed)
	
	# 初始化存档界面
	_setup_save_selection()
	
	# 加载存档数据
	_load_save_data()

func _setup_save_selection():
	"""设置存档选择界面"""
	# 创建存档按钮
	for i in range(save_slots):
		# 创建水平容器来放置存档按钮和清除按钮
		var slot_container = HBoxContainer.new()
		
		# 创建存档按钮
		var save_button = Button.new()
		save_button.text = "存档槽 " + str(i + 1)
		save_button.custom_minimum_size = Vector2(250, 60)
		save_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		save_button.pressed.connect(_on_save_slot_selected.bind(i))
		
		# 创建清除按钮
		var clear_button = Button.new()
		clear_button.text = "清除"
		clear_button.custom_minimum_size = Vector2(60, 60)
		clear_button.pressed.connect(_on_clear_slot_pressed.bind(i))
		
		# 添加到容器
		slot_container.add_child(save_button)
		slot_container.add_child(clear_button)
		save_buttons_container.add_child(slot_container)

func _load_save_data():
	"""加载存档数据"""
	var save_file_path = "user://save_data.json"
	if FileAccess.file_exists(save_file_path):
		var file = FileAccess.open(save_file_path, FileAccess.READ)
		if file != null:
			var json_string = file.get_as_text()
			file.close()
			
			var json = JSON.new()
			var parse_result = json.parse(json_string)
			if parse_result == OK:
				save_data = json.data
				_update_save_buttons()
			else:
				print("存档数据解析失败")

func _update_save_buttons():
	"""更新存档按钮显示"""
	for i in range(save_slots):
		var slot_container = save_buttons_container.get_child(i)
		var save_button = slot_container.get_child(0)  # 存档按钮
		var clear_button = slot_container.get_child(1)  # 清除按钮
		var slot_key = "slot_" + str(i)
		
		if save_data.has(slot_key) and save_data[slot_key] != null:
			# 存档存在，显示存档信息
			var slot_data = save_data[slot_key]
			var level = slot_data.get("level", 1)
			var play_time = slot_data.get("play_time", "00:00:00")
			save_button.text = "存档槽 " + str(i + 1) + "\n等级: " + str(level) + "\n游戏时间: " + play_time
			clear_button.disabled = false  # 启用清除按钮
		else:
			# 空存档槽
			save_button.text = "存档槽 " + str(i + 1) + "\n[空存档]"
			clear_button.disabled = true  # 禁用清除按钮

func _save_game_data(slot_index: int):
	"""保存游戏数据到指定存档槽"""
	var slot_key = "slot_" + str(slot_index)
	var current_time = Time.get_datetime_string_from_system()
	
	# 创建存档数据
	var slot_data = {
		"level": 1,  # 默认等级
		"play_time": "00:00:00",  # 默认游戏时间
		"save_time": current_time,
		"scene": "res://scene/scene1.tscn",  # 默认场景
		"player_position": {"x": 1088, "y": 514}  # 默认位置
	}
	
	save_data[slot_key] = slot_data
	
	# 保存到文件
	var save_file_path = "user://save_data.json"
	var file = FileAccess.open(save_file_path, FileAccess.WRITE)
	if file != null:
		var json_string = JSON.stringify(save_data)
		file.store_string(json_string)
		file.close()
		print("游戏数据已保存到存档槽 ", slot_index + 1)
		_update_save_buttons()
	else:
		print("保存失败：无法创建存档文件")

func _load_game_data(slot_index: int):
	"""从指定存档槽加载游戏数据"""
	var slot_key = "slot_" + str(slot_index)
	
	if save_data.has(slot_key) and save_data[slot_key] != null:
		# 存档存在，加载数据
		var slot_data = save_data[slot_key]
		var scene_path = slot_data.get("scene", "res://scene/scene1.tscn")
		
		# 使用GameSaveManager加载完整的游戏数据
		if GameSaveManager != null:
			var load_success = GameSaveManager.load_game_from_slot(slot_index)
			if load_success:
				print("成功加载存档槽 ", slot_index + 1, " 的数据")
				# 切换到保存的场景
				get_tree().change_scene_to_file(scene_path)
				return
			else:
				print("加载存档槽 ", slot_index + 1, " 失败，开始新游戏")
		
		# 如果加载失败，设置玩家数据到管理器作为备用
		if PlayerManager != null:
			var player_pos = slot_data.get("player_position", {"x": 1088, "y": 514})
			PlayerManager.set_default_spawn_position(Vector2(player_pos.x, player_pos.y))
		
		# 切换到游戏场景
		get_tree().change_scene_to_file(scene_path)
		print("加载存档槽 ", slot_index + 1, " 完成")
	else:
		# 空存档槽，创建新游戏
		_save_game_data(slot_index)
		# 设置GameSaveManager的当前存档槽
		if GameSaveManager != null:
			GameSaveManager.set_current_save_slot(slot_index)
		_start_new_game()

func _start_new_game():
	"""开始新游戏"""
	# 重置玩家数据
	if PlayerManager != null:
		PlayerManager.set_default_spawn_position(Vector2(1088, 514))
	
	# 切换到第一个场景
	get_tree().change_scene_to_file("res://scene/scene1.tscn")
	
func _on_start_button_pressed():
	"""开始游戏按钮点击事件"""
	print("点击开始游戏")
	# 显示存档选择界面
	save_selection_panel.visible = true

func _on_help_button_pressed():
	"""帮助按钮点击事件"""
	print("点击帮助")
	# TODO: 实现帮助界面
	OS.alert("帮助功能待实现")

func _on_settings_button_pressed():
	"""设置按钮点击事件"""
	print("点击设置")
	# TODO: 实现设置界面
	OS.alert("设置功能待实现")

func _on_quit_button_pressed():
	"""退出按钮点击事件"""
	print("点击退出游戏")
	# 退出前自动保存游戏
	_save_before_quit()

func _save_before_quit():
	"""退出前保存游戏"""
	if GameSaveManager != null and GameSaveManager.current_save_slot >= 0:
		print("退出前自动保存游戏...")
		var save_success = GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		if save_success:
			print("游戏保存成功，正在退出...")
		else:
			print("游戏保存失败，仍将退出...")
	else:
		print("没有活跃的存档槽，直接退出游戏")
	
	# 退出游戏
	get_tree().quit()

func _on_back_button_pressed():
	"""返回按钮点击事件"""
	print("返回主菜单")
	# 隐藏存档选择界面
	save_selection_panel.visible = false

func _on_save_slot_selected(slot_index: int):
	"""存档槽选择事件"""
	print("选择存档槽: ", slot_index + 1)
	_load_game_data(slot_index)

func _on_clear_slot_pressed(slot_index: int):
	"""清除存档槽按钮点击事件"""
	var slot_key = "slot_" + str(slot_index)
	
	# 检查存档是否存在
	if not save_data.has(slot_key) or save_data[slot_key] == null:
		return
	
	# 显示确认对话框
	_show_clear_confirmation(slot_index)

func _show_clear_confirmation(slot_index: int):
	"""显示清除存档确认对话框"""
	var confirmation_dialog = AcceptDialog.new()
	confirmation_dialog.dialog_text = "确定要清除存档槽 " + str(slot_index + 1) + " 吗？\n此操作无法撤销！"
	confirmation_dialog.title = "确认清除存档"
	
	# 添加取消按钮
	confirmation_dialog.add_cancel_button("取消")
	confirmation_dialog.get_ok_button().text = "确认清除"
	
	# 连接确认信号
	confirmation_dialog.confirmed.connect(_clear_save_slot.bind(slot_index))
	
	# 添加到场景并显示
	add_child(confirmation_dialog)
	confirmation_dialog.popup_centered()
	
	# 对话框关闭后自动删除
	confirmation_dialog.tree_exited.connect(confirmation_dialog.queue_free)

func _clear_save_slot(slot_index: int):
	"""清除指定存档槽"""
	var slot_key = "slot_" + str(slot_index)
	
	# 从存档数据中移除
	if save_data.has(slot_key):
		save_data.erase(slot_key)
	
	# 保存到文件
	var save_file_path = "user://save_data.json"
	var file = FileAccess.open(save_file_path, FileAccess.WRITE)
	if file != null:
		var json_string = JSON.stringify(save_data)
		file.store_string(json_string)
		file.close()
		print("存档槽 ", slot_index + 1, " 已清除")
		_update_save_buttons()
	else:
		print("清除失败：无法写入存档文件")
